const jwt = require("jsonwebtoken");
const secret = "TxkFzaWhS2ZWPej9pc8Am83WDGQDNHS9";

// 生成token
const generateToken = (data) => {
    return jwt.sign(data, secret, {
        expiresIn: "1h",
    });
};

// 验证token
const verifyToken = (token) => {
    try {
        return jwt.verify(token, secret);
    } catch (error) {
        return false;
    }
};

// 获取token中的数据
const getTokenData = (token) => {
    if (verifyToken(token)) {
        const { _id, username } = verifyToken(token);
        return { _id, username };
    }
    return {};
};

module.exports = { generateToken, verifyToken, getTokenData };
